package com.minigame.rpc.network.command;

import io.netty.buffer.ByteBuf;

import java.nio.charset.StandardCharsets;

public abstract class AbstractCommand<T> {

    private byte version;
    private short command;
    private int id;
    private short headLength;
    private int bodyLength;
    private byte[] heads;
    private byte[] bodys;

    protected abstract void encode(ByteBuf byteBuf,T t);

    protected abstract  T decode(ByteBuf byteBuf);

    protected abstract int command();


    protected void encodeString(ByteBuf byteBuf,String str){
        short len = 0;
        byte[] array = null;
        if(str != null){
            array = str.getBytes(StandardCharsets.UTF_8);
            len = (short) array.length;
        }
        byteBuf.writeShort(len);
        if(array != null){
            byteBuf.writeBytes(array);
        }
    }

    protected String decodeString(ByteBuf byteBuf){
        short len = byteBuf.readShort();
        String ret = null;
        if(len > 0){
            byte[] data = new byte[len];
            byteBuf.readBytes(data);
            ret = new String(data,StandardCharsets.UTF_8);
        }
        return ret;
    }

    public byte getVersion() {
        return version;
    }

    public void setVersion(byte version) {
        this.version = version;
    }

    public short getCommand() {
        return command;
    }

    public void setCommand(short command) {
        this.command = command;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public short getHeadLength() {
        return headLength;
    }

    public void setHeadLength(short headLength) {
        this.headLength = headLength;
    }

    public int getBodyLength() {
        return bodyLength;
    }

    public void setBodyLength(int bodyLength) {
        this.bodyLength = bodyLength;
    }

    public byte[] getHeads() {
        return heads;
    }

    public void setHeads(byte[] heads) {
        this.heads = heads;
    }

    public byte[] getBodys() {
        return bodys;
    }

    public void setBodys(byte[] bodys) {
        this.bodys = bodys;
    }
}
